package com.yeskery.nut.extend.auth;

import com.yeskery.nut.core.*;
import com.yeskery.nut.util.CrossUtils;

import java.util.Collection;
import java.util.Optional;

/**
 * 跨域认证插件
 * @author YESKERY
 * 2024/6/19
 */
public class CrossAuthPlugin extends AbstractAuthPlugin {

    /** 跨域配置集合对象 */
    private final Collection<CrossConfiguration> crossConfigurations;

    /**
     * 构建跨域认证插件
     * @param crossConfigurations 跨域配置集合对象
     */
    public CrossAuthPlugin(Collection<CrossConfiguration> crossConfigurations) {
        if (crossConfigurations == null || crossConfigurations.isEmpty()) {
            throw new NutException("CrossConfiguration Can Not Be Empty.");
        }
        this.crossConfigurations = crossConfigurations;
    }

    @Override
    public boolean beforeHandle(Request request, Response response, Execution execution, Controller controller) throws Exception {
        boolean noAuth = super.beforeHandle(request, response, execution, controller);
        if (noAuth) {
            return true;
        }
        if (request.getMethod() == Method.OPTIONS) {
            Optional<CrossConfiguration> optional = CrossUtils.getRequestCross(crossConfigurations, request, response, true);
            if (optional.isPresent()) {
                return false;
            } else {
                throw new ResponseNutException(ResponseCode.FORBIDDEN);
            }
        } else {
            Optional<CrossConfiguration> optional = CrossUtils.getRequestCross(crossConfigurations, request, response, false);
            if (optional.isPresent()) {
                return true;
            } else {
                throw new ResponseNutException(ResponseCode.FORBIDDEN);
            }
        }
    }
}
